package lnu.project.cart.provider;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import lnu.project.cart.content.BasketContentProvider;
import lnu.project.cart.content.ProductContentProvider;
import lnu.project.cart.entity.Basket;
import lnu.project.cart.entity.Product;

public class BasketProvider implements IBasketProvider {
	private Activity mActivity;
	private static final String[] mContent = new String[] { Basket.ID,
			Basket.NAME };
	

	@Override
	public void Create(Basket b) {
		System.out.println("Create Basket");
		ContentValues values = new ContentValues(1);

		values.put(Basket.NAME, b.getName());
		
		mActivity.getContentResolver().insert(
				BasketContentProvider.CONTENT_BASKET_URI, values);
	}
	
	@Override
	public List<Basket> GetAll() {
		System.out.println("Get all");
		List<Basket> baskets = new ArrayList<Basket>();
		Cursor mCursor = mActivity.managedQuery(BasketContentProvider.CONTENT_BASKET_URI,
				mContent, null, null, null);
		if (mCursor.moveToFirst()) {
			do {
				baskets.add(new Basket(mCursor.getLong(0), mCursor
						.getString(1)));
			} while (mCursor.moveToNext());
		}
		return baskets;
	}
	

	@Override
	public Basket Get(long id) {
		System.out.println("Id:"+id);
		Cursor mCursor = mActivity.managedQuery(BasketContentProvider.CONTENT_BASKET_URI,
				mContent, null, null, null);
		
		
		if (mCursor.moveToFirst()) {
			do {
				if (mCursor.getLong(0) == id) {

					System.out.println("id in if:"+id);
					return new Basket(mCursor.getLong(0),
							mCursor.getString(1));
				}
			} while (mCursor.moveToNext());
		}

		
		return null;
	}
	


	@Override
	public void Update(Basket b) {
		ContentValues values = new ContentValues(1);

		values.put(Basket.NAME, b.getName());
		
		String searchId = Basket.ID + "=" + b.getId();
		mActivity.getContentResolver().update(
				BasketContentProvider.CONTENT_BASKET_URI, values, searchId, null);
	}

	

	@Override
	public void Delete(long id) {
		Cursor mCursor = mActivity.managedQuery(BasketContentProvider.CONTENT_BASKET_URI,
				mContent, null, null, null);
		System.out.println("id:"+id);
		String searchBasketId = Basket.ID + "=" + id;

					mActivity.getContentResolver().delete(
							BasketContentProvider.CONTENT_BASKET_URI, searchBasketId, null);
	}
	
	

	
	public void DeleteALL() {
		Cursor mCursor = mActivity.managedQuery(BasketContentProvider.CONTENT_BASKET_URI,
				mContent, null, null, null);
		
		if (mCursor.moveToFirst()) {
			do {
							
					mActivity.getContentResolver().delete(
							BasketContentProvider.CONTENT_BASKET_URI, null, null);
				
			} while (mCursor.moveToNext());
		}
	}
	
	public void SetActivity(Activity mActivity) {
		this.mActivity = mActivity;
	}

}
